import json
from multiprocessing.pool import ThreadPool

import math
import pandas as pd
import requests

from Spider.config import CONFIG
from Spider.stack import get_stacks
from Spider.tool import cal_run_time


def extract_a_close(a_code):
    """


    :param a_code: 6位a股号 600998
    :return:
    """
    para_code = "sh" + str(a_code)
    return __extract_close20(para_code)


def extract_h_close(h_code):
    """

    :param h_code:  0998.hk
    :return:
    """
    para_code = "hk0" + str(h_code[:-3])
    return __extract_close20(para_code)


def __extract_close20(para_code):
    """
    提取前20天收盘价

    :param para_code:
    :return:
    """
    data_num = 50
    if para_code[:2] == "sh":
        url = 'http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={},day,,,{},qfq'.format(para_code, data_num)
    else:
        url = 'http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?param={},day,,,{},qfq'.format(para_code, data_num)
    html = requests.get(url).content
    dic = json.loads(html)
    data = dic['data'][para_code]['qfqday']
    date = [d[0] for d in data]
    close20 = [d[2] for d in data]
    return date, close20


def get_last20mean(stack):
    """
    获取前n天的股票1均价

    :param stack:
    :return:
    """
    try:
        acode = stack["s_acode"]
        hcode = stack["s_hcode"]
        adate, aclose = extract_a_close(acode)
        hdate, hclose = extract_h_close(hcode)
        dfa = pd.DataFrame({})
        dfa["date"] = adate
        dfa["aclose"] = aclose
        dfh = pd.DataFrame({})
        dfh["date"] = hdate
        dfh["hclose"] = hclose
        df_merge = dfa.merge(dfh, on="date", how="outer", suffixes=("_a", "_h"), sort=True)
        # 去除a股没有数据的
        df_merge = df_merge.dropna(subset=["aclose"])
        # a股前n天
        df_merge = df_merge.iloc[CONFIG.LAST_N_DAY_MEAN:, ]
        # 去除h股没有数据的
        df_merge.dropna(subset=["hclose"])
        df_merge["aclose"] = df_merge["aclose"].astype(float)
        df_merge["hclose"] = df_merge["hclose"].astype(float)
        df_merge["a:b"] = df_merge["aclose"] / df_merge["hclose"]
        s_mean20 = df_merge["a:b"].mean()
        s_mean20 = round(s_mean20, 3)
        if math.isnan(s_mean20):
            return
        requests.patch("{}/index/api/stack/{}/".format(CONFIG.LOCAL_URL, stack["s_acode"]),
                       data={"s_20mean": s_mean20})
        return
    except Exception as e:
        return


@cal_run_time(cal_func_place="更新a股前10天平均值")
def update_stack_close20():
    """
    更新a股前10天的平均值

    :return:
    """

    stacks = get_stacks()
    task_pool = ThreadPool(60)
    task_pool.map(get_last20mean, stacks)
    # for s_mean20, stack in tqdm(zip(s_mean20s, stacks)):
    #     requests.patch("{}/index/api/stack/{}/".format(CONFIG.LOCAL_URL, stack["s_acode"]),
    #                    data={"s_20mean": s_mean20})


if __name__ == '__main__':
    update_stack_close20()
